package sjc;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CacheListenerDemo {
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3, Integer.MAX_VALUE);
        CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.72.133:2181", 3000, 3000, retryPolicy);
        client.start();

        System.out.println("完成zookeeper的链接。。");

        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/test", true);

        //添加监听
        PathChildrenCacheListener listener = new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
                System.out.println("监听的子节点发生了变化，发生了事件通知: " + event);
            }
        };

        pathChildrenCache.getListenable().addListener(listener);
        pathChildrenCache.start();

        System.out.println("完成子节点监听器的注册和启动");

        Thread.sleep(1000 * 120);
    }
}
